from rest_framework import serializers
from  questions_app.models import Question

class AnswerSerializer(serializers.ModelSerializer):
    '''单个问题查询回答序列化器'''
    nick_name = serializers.CharField(source='user.nickname')
    create_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S')

    class Meta:
        model = Question
        fields = ['nick_name','content','create_time']

class QuestionSerializer(serializers.ModelSerializer):
    '''问题序列化器'''
    nick_name = serializers.CharField(source='user.nickname')
    course_name = serializers.CharField(source='section.chapter.stage.course.name')
    stage_name = serializers.CharField(source='section.chapter.stage.name')
    chapter_name = serializers.CharField(source='section.chapter.name')
    section_name = serializers.CharField(source='section.name')
    create_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S')
    #该回答是对象
    answers = AnswerSerializer(many=True,read_only=True,source='children')
    class Meta:
        model = Question
        fields = '__all__'

#一个章节的问题序列化器
class OneSectionQuestionSerializer(serializers.ModelSerializer):
    nick_name = serializers.CharField(source='user.nickname')
    create_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S')
    #该回答是对象
    answers = AnswerSerializer(many=True,read_only=True,source='children')
    class Meta:
        model = Question
        fields = '__all__'

class AddQuestionViewSerializer(serializers.ModelSerializer):
    '''提问序列化器'''
    title = serializers.CharField(max_length=20)
    content = serializers.CharField(max_length=1000,allow_blank=True,allow_null=True)

    section = serializers.IntegerField()

    class Meta:
        model = Question
        fields = ['title','content','section']

class AnswerQuestionSerializer(serializers.ModelSerializer):
    '''回答序列化器'''
    content = serializers.CharField(max_length=1000,allow_blank=True,allow_null=True)
    question = serializers.IntegerField()
    section = serializers.IntegerField()

    class Meta:
        model = Question
        fields = ['content','question','section']